package com.cc.service.impl;

import com.cc.dao.AttendanceDao;
import com.cc.dao.impl.AttendanceDaoImpl;
import com.cc.entity.AttendanceRecord;
import com.cc.entity.Page;
import com.cc.service.AttendanceService;
import org.apache.log4j.Logger;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class AttendanceServiceImpl implements AttendanceService {
    private static final Logger log = Logger.getLogger(AttendanceServiceImpl.class);
    private AttendanceDao attendanceDao = new AttendanceDaoImpl();
    @Override
    public Map<String, Object> isClockIn(String employeeId) {
        Map<String, Object> result = new HashMap<>();

        // 判断是否已经打卡
        if(attendanceDao.isClockIn(employeeId)){
            result.put("code", "200");
            result.put("msg", "已打卡");
            result.put("alreadyClockIn", true);
            return result;
        }

        // 未打卡则执行打卡
        try {
            attendanceDao.clockIn(employeeId);
            result.put("code", "200");
            result.put("msg", "打卡成功");
            result.put("alreadyClockIn", false);
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "打卡失败: " + e.getMessage());
            result.put("alreadyClockIn", false);
        }

        return result;
    }

    @Override
    public Page<AttendanceRecord> getAttendanceRecords(Integer employeeId, Page page) {
        return attendanceDao.getAttendanceRecord(employeeId, page);
    }

    @Override
    public int getAttendanceTotal(Integer employeeId) {
        return attendanceDao.getTotal(employeeId);
    }

    @Override
    public Map<String, Object> getAttendanceOverview(Integer employeeId) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取基础数据
            Map<String, Object> overview = attendanceDao.getAttendanceOverview(employeeId);

            // 计算工作日和出勤率
            LocalDate now = LocalDate.now();
            int year = now.getYear();
            int month = now.getMonthValue();
            int workDays = calculateWorkDays(year, month);
            int attendanceDays = (int) overview.get("attendanceDays");
            double attendanceRate = Math.round((attendanceDays * 100.0 / workDays) * 10) / 10.0;

            // 计算加班费（假设每小时50元）
            double overtimeHours = (double) overview.get("overtimeHours");
            double overtimePay = overtimeHours * 50;

            // 获取最近迟到记录详情
            AttendanceRecord lastLate = (AttendanceRecord) overview.get("lastLateRecord");
            int lastLateMinutes = 0;
            String lastLateDate = null;
            if (lastLate != null && lastLate.getCheckInTime() != null && lastLate.getDate() != null) {
                // 计算迟到分钟数（假设9点为上班时间）
                Calendar cal = Calendar.getInstance();
                cal.setTime(lastLate.getCheckInTime());
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);
                lastLateMinutes = (hour - 9) * 60 + minute;

                // 格式化日期
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                lastLateDate = sdf.format(lastLate.getDate());
            }

            // 构建返回结果
            result.put("attendanceDays", attendanceDays);
            result.put("attendanceRate", attendanceRate);
            result.put("lateCount", overview.get("lateCount"));
            result.put("lastLateDate", lastLateDate);
            result.put("lastLateMinutes", lastLateMinutes);
            result.put("leaveDays", overview.get("leaveDays"));
            result.put("annualLeaveLeft", overview.get("annualLeaveLeft"));
            result.put("overtimeHours", overtimeHours);
            result.put("overtimePay", overtimePay);

        } catch (Exception e) {
            log.error("获取考勤概览失败", e);
            throw new RuntimeException("获取考勤概览失败");
        }

        return result;
    }

    @Override
    public int calculateWorkDays(int year, int month) {
        LocalDate start = LocalDate.of(year, month, 1);
        LocalDate end = start.withDayOfMonth(start.lengthOfMonth());

        int workDays = 0;
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            if (date.getDayOfWeek() != DayOfWeek.SATURDAY && date.getDayOfWeek() != DayOfWeek.SUNDAY) {
                workDays++;
            }
        }
        return workDays;
    }
}
